package com.zhangkeyou.map.mapweb.domain.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private Userinfo userinfo;

    private List<String> permissions;

    public LoginUser(Userinfo userinfo, List<String> permissions) {
        this.userinfo = userinfo;
        this.permissions = permissions;
    }



    //放置序列化到redis时出错

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> simpleGrantedAuthorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 避免多次查询时，多次转换
        if(Objects.isNull(simpleGrantedAuthorities))
            simpleGrantedAuthorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return simpleGrantedAuthorities;
    }

    @Override
    public String getPassword() {
        return userinfo.getPassword();
    }

    @Override
    public String getUsername() {
        return userinfo.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
